using System.Collections.Generic;
using System.Linq;
using Demo.Model;
using Demo.Repository;
using Demo.RequestParm;
using Microsoft.AspNetCore.Mvc;

namespace Demo.Controllers
{
    public class ProductrController : Controller
    {

            public IActionResult Index(){
                var productRep=new EfRepository<Product>();
                var products=productRep.Table.Where(x=>x.IsDeleted==false).ToList();
                return View(products);
            }
            public IActionResult CreateOrEdit(int id){
                var productRep=new EfRepository<Product>();
                var products=productRep.Table.Where(x=>x.Id==id).FirstOrDefault();
                return View(products);
            }
            [HttpPost]
            
            public IActionResult Delete(int id){
                var productRep=new EfRepository<Product>();
                productRep.Delete(id);
                return RedirectToAction("Index");
            }
            public IActionResult Save(RequestProduct model){
                var productRep=new EfRepository<Product>();
                      var products=productRep.Table.Where(x=>x.IsDeleted==false).FirstOrDefault();
                    if(model.Id>0){
                        if(model!=null){
                            products.ProductName=model.ProductName;
                            products.Supplier=model.Supplier;
                            products.Price=model.Price;
                            products.Stock=model.Stock;
                            products.Remarks=model.Remarks;
                    
                        }
                    }else{
                        new Product{
                            ProductName=model.ProductName,
                            Supplier=model.Supplier,
                            Price=model.Price,
                            Stock=model.Stock,
                            Remarks=model.Remarks
                        };
                    }
                    return Ok();
                    
            }
            
            public IActionResult Query(ProductRequest request){
                var productRep=new EfRepository<Product>();
                List<Product> products;
                if(request!=null&&request.Keyword!=null&&request.Keyword.Length>0){
                    products=productRep.Table.Where(x=>x.IsDeleted==false&&(x.ProductName.Contains(request.Keyword)||x.Remarks.Contains(request.Keyword))).ToList();
                }else{
                     products=productRep.Table.Where(x=>x.IsDeleted==false).ToList();
                }
            return Json(products);
            }
    }}
